#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "socket.h"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cassert>

CSocket::CSocket(const std::string& localIp, int localPort,const SocketType &type,const std::string& peerIp,int peerPort)
{
    assert(!localIp.empty() && localPort > 0);

    if(type == SocketType::TCP)
    {
        m_type = SOCK_STREAM;
    }
    else if(type == SocketType::UDP)
    {
        m_type = SOCK_DGRAM;
    }    
    m_sfd = socket(AF_INET, m_type, 0);

    memset(&m_peerAddrIn,0,sizeof(m_peerAddrIn));
    memset(&m_localAddrIn,0,sizeof(m_peerAddrIn));
    m_peerAddrIn.sin_family=AF_INET;//设置协议集
    m_localAddrIn.sin_family=AF_INET;//设置协议集
    if(!localIp.empty() && localPort > 0)
    {
        m_localAddrIn.sin_port = htons(localPort);
        m_localAddrIn.sin_addr.s_addr = inet_addr(localIp.c_str());
    }

    if(!peerIp.empty() && peerPort > 0)
    {
        m_peerAddrIn.sin_port = htons(peerPort);
        m_peerAddrIn.sin_addr.s_addr = inet_addr(peerIp.c_str());
    }
}

CSocket::~CSocket()
{
    Close();
}

void CSocket::Send(const Buffer &data) const
{
    if(m_type==SOCK_STREAM)
    {
        int send_num=send(m_sfd,&(*data.begin()),date.size(),0);
        if(send_num==-1)
        {
            perror("send error:");
            return 1;
        }
    }
        
}

void CSocket::Recv(Buffer &data) const
{
}

bool CSocket::Listening(int blockNum)
{
    return false;
}

bool CSocket::Connect()
{
    return false;
}

bool CSocket::Close()
{
    return false;
}
